package com.server.questionbank.snframe.controller.Course.Resource;

import com.server.questionbank.snframe.controller.Course.pojo.Resource.CreateCourseResource;
import com.server.questionbank.snframe.domain.Course.Member.CoursePermission;
import com.server.questionbank.snframe.domain.Course.Resource.CourseFiles;
import com.server.questionbank.snframe.domain.Course.Resource.CourseResource;
import com.server.questionbank.snframe.domain.Course.Result.CourseResourceInfo;
import com.server.questionbank.snframe.domain.Course.TCourse;
import com.server.questionbank.snframe.domain.ResDTO.ResponseResult;
import com.server.questionbank.snframe.domain.User.TUser;
import com.server.questionbank.snframe.service.CourseService.Member.CusMemberService;
import com.server.questionbank.snframe.service.CourseService.Resource.CourseFileService;
import com.server.questionbank.snframe.service.CourseService.Resource.CourseResourceService;
import com.server.questionbank.snframe.service.CourseService.TCourseService;
import com.server.questionbank.snframe.service.UsersService.UsersService;
import com.server.questionbank.snframe.util.MinIo.ProgressInputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/course/resource")
public class CourseResourceController {
    @Autowired
    private UsersService usersService;
    @Autowired
    private CourseResourceService courseResourceService;
    @Autowired
    private TCourseService tCourseService;
    @Autowired
    private CusMemberService cusMemberService;
    @Autowired
    private CourseFileService courseFileService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    // 创建资源
    @PostMapping("/create")
    public ResponseResult<Long> create(@RequestBody CreateCourseResource courseResource) {
        if (courseResource == null) return ResponseResult.error();
        TUser  user = usersService.getLoginUser();
        if (user == null) return ResponseResult.error("未登录，请先登录");
        if (!courseResourceService.createResource(courseResource, user.getUserId())) return ResponseResult.error("创建资源失败!");
        return ResponseResult.success(courseResource.getResourceId());
    }

    // 获取资源信息
    @PostMapping("/getResourceInfo")
    public ResponseResult<CourseResourceInfo> getResourceInfo(@RequestBody Map<String, Long> map) throws Exception {
        Long resourceId = map.get("resourceId");
        if (resourceId == null) return ResponseResult.error("资源ID不能为空");
        CourseResourceInfo info = courseResourceService.getResourceInfo(resourceId);
        if (info == null) return ResponseResult.error("资源不存在");
        return ResponseResult.success(info);
    }

    // 上传资源文件
    @PostMapping("/upload")
    public ResponseResult<Boolean> upload(@RequestParam("file") MultipartFile file, @RequestParam("resource") Long resourceId) throws Exception {
        if (file == null) return ResponseResult.error();
        TUser  user = usersService.getLoginUser();
        if (user == null) return ResponseResult.error("未登录，请先登录");
        CourseResource courseResource = courseResourceService.getResourceInfo(resourceId);
        if (courseResource == null) return ResponseResult.error("资源不存在");
        if (!user.getUserId().equals(courseResource.getUploadUserId())) return ResponseResult.error("没有权限");

        try {
            courseResourceService.uploadFlie(file, courseResource);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseResult.success(true);
    }

    @GetMapping("/download")
    public void download(
            @RequestParam Long fileId,
            @RequestParam(required = false) Long start,
            @RequestParam(required = false) Long end,
            HttpServletResponse response) throws Exception {

        TUser user = usersService.getLoginUser();
        if (user == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("未登录，请先登录");
            return;
        }

        CourseResourceInfo courseResource = courseResourceService.getResourceInfoByFileId(fileId);
        if (courseResource == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getWriter().write("资源不存在");
            return;
        }

        TCourse course = tCourseService.getCourseById(courseResource.getCourseId());
        CoursePermission permission = cusMemberService.getMemberPermission(course.getCourseId(), user.getUserId());
        if (!Objects.equals(course.getCreateBy(), user.getUserId()) && (permission == null || permission.getPermissionFlags() < 1)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write("您没有权限下载此文件");
            return;
        }

        CourseFiles file = courseFileService.getFileInfo(fileId);
        if (file == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getWriter().write("文件不存在");
            return;
        }

        try (InputStream inputStream = (start != null && end != null)
                ? courseResourceService.downloadFile(file.getFilePath(), start, end)
                : courseResourceService.downloadFile(file.getFilePath())) {
            ProgressInputStream progressInputStream = new ProgressInputStream(
                    inputStream,
                    file.getFileSize(),  // Assuming fileId is the total file size
                    progress -> { },
                    "download_course_resource_" + user.getUserId() + "_" + fileId,
                    redisTemplate
            );
            String encodedFileName = URLEncoder.encode(file.getFileName(), "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + encodedFileName);
            response.setContentType("application/octet-stream");

            progressInputStream.transferTo(response.getOutputStream());
            response.flushBuffer();

        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("文件下载失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
